package com.konsung.ui;

import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.decard.healthcard.WSRead;
import com.decard.portdrivelibrary.utils.DigitalTrans;
import com.example.mtreader.MainActivity;
import com.google.gson.reflect.TypeToken;
import com.huada.healthcard.HuaDaDeviceLib;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.konsung.bean.CheckData;
import com.konsung.bean.ConfigDataRespone;
import com.konsung.bean.FlagModel;
import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.bean.QueryItem;
import com.konsung.greendaoUtil.ConfigDtoDao;
import com.konsung.greendaoUtil.DBUtitl;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.MySQLiteOpenHelper;
import com.konsung.healthfile.R;
import com.konsung.kslibrary.base.BaseActivity;
import com.konsung.kslibrary.base.MvpView;
import com.konsung.network.RequestUtils;
import com.konsung.network.URLManage;
import com.konsung.network.UploadData;
import com.konsung.presenter.HealthFilePresenter;
import com.konsung.presenter.impl.HealthFilePresenterImpl;
import com.konsung.provide.ProviderReader;
import com.konsung.ui.adapter.GvMeasureAdapter;
import com.konsung.ui.adapter.PatientListAdapter;
import com.konsung.ui.defineview.HeadRefreshView;
import com.konsung.ui.defineview.LoadMoreView;
import com.konsung.ui.defineview.LoadingDialog;
import com.konsung.ui.defineview.PopupDialog;
import com.konsung.ui.defineview.SelectDialog;
import com.konsung.util.BroadcastUtils;
import com.konsung.util.ConvertUtils;
import com.konsung.util.IdCardUtil;
import com.konsung.util.JsonUtil;
import com.konsung.util.KParamType;
import com.konsung.util.MeasureUtil;
import com.konsung.util.SpUtils;
import com.konsung.util.ToastUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.konsung.util.constant.GlobalConstant.IDCARD;

/**
 * 健康档案主界面
 */
public class HealthFileActivity extends BaseActivity<HealthFilePresenterImpl> implements
        HealthFilePresenter.View, MvpView, DatePickerDialog.OnDateSetListener,
        DialogInterface.OnClickListener {

    @BindView(R.id.iv_head_photo)
    ImageView ivHeadPhoto;
    @BindView(R.id.tv_no_patient)
    TextView tvNoPatient;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @BindView(R.id.tv_patient_age)
    TextView tvPatientAge;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_measure_time)
    TextView tvMeasureTime;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.ll_current_patient_info)
    LinearLayout llCurrentPatientInfo;
    @BindView(R.id.iv_modify)
    ImageView ivModify;
    @BindView(R.id.iv_report)
    ImageView ivReport;
    @BindView(R.id.gv_measure)
    GridView gvMeasure;
    @BindView(R.id.et_query_condition)
    EditText etQueryCondition;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.iv_query)
    ImageView ivQuery;
    @BindView(R.id.tv_total_patient)
    TextView tvTotalPatient;
    @BindView(R.id.cbx_all_select)
    CheckBox cbxAllSelect;
    @BindView(R.id.iv_close)
    ImageView ivDelete;
    @BindView(R.id.lv_patient_list)
    ListView lvPatientList;
    @BindView(R.id.refresh_patient_layout)
    PullToRefreshLayout refreshLayout;
    @BindView(R.id.btn_select)
    Button btnSelect;
    @BindView(R.id.btn_download)
    Button btnDownload;

    DatePickerDialog datePickerDialog; //时间选择弹出框
    @BindView(R.id.tv_file_state)
    TextView tvFileState;
    private Calendar calendar;
    private TextView tvCurrentTime;
    private SimpleDateFormat sdf;
    private boolean runThread;
    List<PatientBean> patientBeen;
    PatientListAdapter patientAdapter;
    List<String> gvMeasureData; //当前居民最新的测量数据数组
    GvMeasureAdapter gvMeasureAdapter; //最新测量数据的设配器
    PopupDialog popupDialog;
    private HuaDaDeviceLib huaDaDeviceLib;
    private MainActivity mtReader;
    private boolean isUsbConnectedDevice; //usb是否有连接设备
    private boolean isShowHealthFile; //健康档案界面显示
    private WSRead dkRead; //德卡
    private boolean isAllSelected;
    private Date tempStart;
    private Date tempStop;
    private String tempContent = "";
    private int tempUploadState = 0; // 0全部 1未上传 2已上传 默认选择全部
    private int tempSex = -1; // -1全部  1男 0女   默认选择全部
    private boolean tempIsQuery = true; //true为查询 false为筛选
    BrushCardThread brushCardThread;
    PatientBean currentPatient;
    private long allSize;
    private LoadingDialog loadingDialog;
    private boolean isShowAddPatient; //新增居民是否显示状态
    private boolean isReset = false; //是否重置，重置提示语需区分
    private SelectDialog selectDialog; //筛选弹窗
    private boolean isAddNewUser = false; //标识是否是新增用户

    CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            patientAdapter.setAllDeleteState(isChecked);
            isAllSelected = isChecked;
        }
    };
    DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == 4) { //f1
                if (loadingDialog.isShowing()) {
                    return true;
                }
                UiUtils.hideProgress();
            }
            return false;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_file);
        initConfig(); //初始化配置
        ButterKnife.bind(this);
        sdf = UiUtils.getDateFormat(UiUtils.DateState.SHORT);
        calendar = Calendar.getInstance();
        datePickerDialog = new DatePickerDialog(this, R.style.AppDate, this,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        bindEvent();
        patientBeen = new ArrayList<>();
        patientAdapter = new PatientListAdapter(this, patientBeen, allSize);
        lvPatientList.setAdapter(patientAdapter);
        initReadCardDevice();
        brushCardThread = new BrushCardThread();
        //该线程一直存在，不使用线程池管理
        brushCardThread.start();
        gvMeasureData = new ArrayList<>();
        gvMeasureAdapter = new GvMeasureAdapter(this, gvMeasureData);
        gvMeasure.setAdapter(gvMeasureAdapter);
        refreshLayout.setHeaderView(new HeadRefreshView(this));
        refreshLayout.setFooterView(new LoadMoreView(this));
    }

    /**
     *  初始化配置
     */
    private void initConfig() {
        if (!UiUtils.isConnectNetWork(MyApplication.getContext())) {
            return;
        }
        UiUtils.postLongThread(new Runnable() {
            @Override
            public void run() {
                UiUtils.showProgress(MyApplication.getContext(), getString(R.string
                        .start_data));
                String code = SpUtils.getSp(MyApplication.getContext(), GlobalConstant.APP_CONFIG,
                        GlobalConstant.CONFIG_DATA_CODE, GlobalConstant.DEFAULT_CONFIG_DATA_CODE);
                RequestParams requestParams = new RequestParams();
                requestParams.add("requestType", "CONFIG");
                requestParams.add("requestMessage", code);
                UploadData uploadData = new UploadData(HealthFileActivity.this);
                RequestUtils.clientPost(URLManage.getInstance().configPort,
                        requestParams, new TextHttpResponseHandler() {

                            @Override
                            public void onFailure(int statusCode, Header[]
                                    headers,
                                    String responseString, Throwable
                                    throwable) {
                                Log.d("test", "fail");
                            }

                            @Override
                            public void onSuccess(int statusCode, Header[]
                                    headers, String responseString) {
                                try {
                                    if (responseString != null) {
                                        ConfigDataRespone bean = JsonUtil.toEntity(responseString,
                                                new TypeToken<ConfigDataRespone>() {
                                                }.getType());
                                        if (GlobalConstant.RESULT_CODE_SUCCESS
                                                .equals(bean.getResultCode() + "")) {
                                            String newCode = bean.getEntity() + "";
                                            SpUtils.saveToSp(GlobalConstant.APP_CONFIG,
                                                    GlobalConstant.CONFIG_DATA_CODE, newCode);
                                            List<ConfigDataRespone.ListBean> formList = bean
                                                    .getList();
                                            if (formList.size() > 0) {
                                                ConfigDtoDao configDao = GreenDaoManager
                                                        .getConfigDao(MyApplication.getContext());
                                                configDao.deleteAll();
                                                configDao.insertOrReplaceInTx(ConvertUtils
                                                        .toFormConfigDto(formList, newCode));
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (UiUtils.isShuYangArea()) {
                            tvFileState.setVisibility(View.VISIBLE);
                        } else {
                            tvFileState.setVisibility(View.GONE);
                        }
                    }
                });

                if (SpUtils.getSp(GlobalConstant.APP_CONFIG
                        , GlobalConstant.APP_FIRST_INSTALL, true)) {
                    //数据转换
                    presenter.switchValue();
                    initMeasureData();
                    SpUtils.saveToSp(GlobalConstant.APP_CONFIG, GlobalConstant.APP_FIRST_INSTALL
                            , false);
                }

                UiUtils.hideProgress();
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        isShowHealthFile = true;
        initReceiver();
        BroadcastUtils.sendShowForStartManage();
        //该广播通知健康测量软件，启动刷卡服务
        BroadcastUtils.sendOnStartForHealthMeasure();
        if (MySQLiteOpenHelper.isUploadDb) {
            BroadcastUtils.sendDarkForStartManage();
        }
        //居民下载页面下载数据后才会走该方法刷新列表数据
        if (FlagModel.getInstance().isDownloadData) {
            FlagModel.getInstance().isDownloadData = false;
            isAddNewUser = true;
            tempContent = "";
            tempIsQuery = true;
            tempSex = 0;
            tempUploadState = 0;
            tempStart = null;
            tempStop = null;
            refreshPatient(presenter.getAllPatientBean(0, 10));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        initMeasureData();
        cbxAllSelect.setChecked(false);
        patientAdapter.setAllDeleteState(false);
    }

    /**
     * 初始化读卡器
     */
    private void initReadCardDevice() {
        //初始化华大一体机读卡器
        if (huaDaDeviceLib == null) {
            huaDaDeviceLib = new HuaDaDeviceLib(this);
        }
        huaDaDeviceLib.openDevice();
        //明泰MT6 二合一读卡器
        if (mtReader == null) {
            mtReader = new MainActivity(this);
        }

        mtReader.getMTPermission();
        //初始化德卡读卡器
        if (dkRead == null) {
            dkRead = new WSRead();
        }
        dkRead.usbPermission(this);

        //启动刷卡线程
        runThread = true;
        isUsbConnectedDevice = true;
    }

    /**
     * 注册广播
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(BroadcastUtils.REPLACE_PATIENT);
        filter.addAction(BroadcastUtils.ADD_PATIENT);
        filter.addAction(BroadcastUtils.SHOW_ADDPATIENT);
        filter.addAction(BroadcastUtils.DISMISS_ADDPATIENT);
        //内置读卡器，传递数据
        filter.addAction(BroadcastUtils.HEALRH_MEASURE_CARD_READER);
        filter.addAction(BroadcastUtils.HEALTH_FILE_UPLOAD_DB);
        filter.addAction(BroadcastUtils.HEALTH_FILE_UPLOAD_DB_SUCCESS);
        filter.addAction(BroadcastUtils.REFRSH_PATIENT);
        filter.addAction(BroadcastUtils.SET_CURRENT_PATIENT);
        filter.addAction(BroadcastUtils.REFRESH_NEW_DATA);
        registerReceiver(usbStateReceiver, filter);
        if (MySQLiteOpenHelper.isUploadDb) {
            BroadcastUtils.sendUploadDB();
        }
    }

    /**
     * 绑定点击事件
     */
    private void bindEvent() {
        if (UiUtils.isShuYangArea()) {
            tvFileState.setVisibility(View.VISIBLE);
        } else {
            tvFileState.setVisibility(View.GONE);
        }
        etQueryCondition.setOnClickListener(this);
        ivClear.setOnClickListener(this);
        ivQuery.setOnClickListener(this);
        ivModify.setOnClickListener(this);
        ivReport.setOnClickListener(this);
        ivDelete.setOnClickListener(this);
        btnSelect.setOnClickListener(this);
        btnDownload.setOnClickListener(this);
        cbxAllSelect.setOnCheckedChangeListener(listener);

        etQueryCondition.setCursorVisible(false);
        datePickerDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                UiUtils.hideKeyboard(tvCurrentTime);
            }
        });

        refreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                //每次刷新均为查询全部数据，不带其他条件
                tempIsQuery = true;
                tempContent = "";
                tempStart = null;
                tempStop = null;
                tempUploadState = 0;
                tempSex = 0;
                List<PatientBean> patientBean = presenter.getPatientBean(tempContent, tempStart,
                        tempStop, tempUploadState, tempSex, 0, 10
                        , tempIsQuery);
                if (patientBean != null && patientBean.size() > 0) {
                    patientBeen.clear();
                    patientBeen.addAll(patientBean);
                    patientAdapter.setAllSize(allSize);
                    patientAdapter.notifyDataSetChanged();
                    tvTotalPatient.setText(presenter.getPatientSize(tempContent
                            , tempStart, tempStop));
                    Log.e("xsc_tvtotal_1", "" + tvTotalPatient.getText().toString());
                }
                refreshLayout.finishRefresh();
            }

            @Override
            public void loadMore() { //批量加载更多
                List<PatientBean> patientBean = presenter.getPatientBean(tempContent, tempStart,
                        tempStop, tempUploadState, tempSex, patientBeen.size(), 10
                        , tempIsQuery);
                if (patientBean != null && patientBean.size() > 0) {

                    patientBeen.addAll(patientBean);
                    patientAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showShortToast(R.string.no_more_data);
                }
                refreshLayout.finishLoadMore();
            }
        });
    }

    /**
     * 初始化测量数据
     * 1界面显示调用
     * 2居民切换 广播调用
     */
    public void initMeasureData() {
        if (isAddNewUser) {
            tempContent = "";
            tempIsQuery = true;
            tempSex = 0;
            tempUploadState = 0;
            tempStart = null;
            tempStop = null;
            isAddNewUser = false;
        }
        presenter.getNewestMeasureData(tempContent, tempStart, tempStop);
    }

    /**
     * 重新刷新病人数据
     */
    private void refreshPatient() {
        patientBeen.clear();
        patientBeen.addAll(presenter.getPatientBean(tempContent, tempStart, tempStop
                , tempUploadState, tempSex, 0, 10, tempIsQuery));
        patientAdapter.notifyDataSetChanged();
    }

    @Override
    public void initMeasureData(MeasureDataBean measureData, long size,
            PatientBean currentPatient, String patientSize) {
//        tvTotalPatient.setText(patientSize);

        if (tempIsQuery) {
            tvTotalPatient.setText(presenter.getPatientSize(tempContent
                    , tempStart, tempStop));
        } else {
            tvTotalPatient.setText(presenter.getPatientSizeInSelect(tempSex, tempUploadState
                    , tempStart, tempStop));
        }

        Log.e("xsc_tvtotal_2", "" + tvTotalPatient.getText().toString());
        showMeasureItem(measureData);
        this.currentPatient = currentPatient;
        if (this.allSize < size) { //新增居民时刷新列表
            this.allSize = size;
            patientBeen.clear();
            patientBeen.addAll(presenter.getPatientBean(tempContent, tempStart, tempStop
                    , tempUploadState, tempSex, 0, 10, tempIsQuery));
        }
        patientAdapter.setAllSize(allSize);
        patientAdapter.notifyDataSetChanged();
        UiUtils.setHeadPhoto(ivHeadPhoto, currentPatient);
        if (currentPatient != null) {
            UiUtils.setLongText(tvPatientName, currentPatient.getName());
            tvPatientSex.setText(IdCardUtil.getSexFormDB(currentPatient.getSex()));
            tvPatientAge.setText(currentPatient.getAge() + UiUtils.getString(R.string.year));
            if (currentPatient.getCrimeMeasureDate() != null) {
                tvLeft.setVisibility(View.VISIBLE);
                tvRight.setVisibility(View.VISIBLE);
            } else {
                tvMeasureTime.setText("");
                tvLeft.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
            }
        } else {
            tvPatientName.setText(R.string.current_patient_empty);
            tvPatientSex.setText("");
            tvPatientAge.setText("");
            tvMeasureTime.setText("");
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
        }
    }

    /**
     * 根据设备配置显示测量项
     * @param bean 测量数据
     */
    private void showMeasureItem(MeasureDataBean bean) {
        gvMeasureData.clear();
        int measureConfig;
        int paramValue;
        if (bean == null) {
            measureConfig = ProviderReader.getMeasureConfig(this);
            paramValue = ProviderReader.getDeviceConfig(this);
            bean = new MeasureDataBean();
        } else {
            measureConfig = bean.getMeasureValue();
            paramValue = bean.getParamValue();
            SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState.SHORT);
            String format = dateFormat.format(new Date(bean.getMeasureTime()));
            tvMeasureTime.setText(format);
        }

        String colon = getString(R.string.colon);
        String divide = getString(R.string.unit_divide);
        if ((paramValue & (0x01 << 0)) != 0) { //心电血氧血压
            String ecg = MeasureUtil.formatMeasureData(KParamType.ECG_HR,
                    bean.getTrendValue(KParamType.ECG_HR));
            String spo2 = MeasureUtil.formatMeasureData(KParamType.SPO2_TREND,
                    bean.getTrendValue(KParamType.SPO2_TREND));
            String nibpName = MeasureUtil.getTitleName(KParamType.NIBP_SYS);
            String sysValue = MeasureUtil.measureValueShowUi(KParamType.NIBP_SYS,
                    bean.getTrendValue(KParamType.NIBP_SYS));
            String diaValue = MeasureUtil.measureValueShowUi(KParamType.NIBP_DIA,
                    bean.getTrendValue(KParamType.NIBP_DIA));
            String nibpUnit = MeasureUtil.getValueUnit(KParamType.NIBP_DIA);
            gvMeasureData.add(ecg);
            gvMeasureData.add(spo2);
            gvMeasureData.add(nibpName + colon + " " + sysValue + divide + diaValue + nibpUnit);
        }

        if ((paramValue & (0x01 << 2)) != 0
                || (paramValue & (0x01 << 6)) != 0
                || (paramValue & (0x01 << 7)) != 0
                || (paramValue & (0x01 << 8)) != 0
                || (paramValue & (0x01 << 16)) != 0) { //血糖
            if (bean.getTrendValue(KParamType.BLOODGLU_AFTER_MEAL) != GlobalConstant.INVALID_DATA) {

                String gluValue = MeasureUtil.formatMeasureData(KParamType.BLOODGLU_AFTER_MEAL,
                        bean.getTrendValue(KParamType.BLOODGLU_AFTER_MEAL));
                gvMeasureData.add(gluValue);
            } else {
                String gluValue = MeasureUtil.formatMeasureData(KParamType.BLOODGLU_AFTER_MEAL,
                        bean.getTrendValue(KParamType.BLOODGLU_BEFORE_MEAL));
                gvMeasureData.add(gluValue);
            }
        }
        if ((paramValue & (0x01 << 1)) != 0
                || (paramValue & (0x01 << 9)) != 0
                || (paramValue & (0x01 << 10)) != 0) { //尿常规
            String uriName = MeasureUtil.getTitleName(KParamType.URINERT_LEU);
            String uriMeasure;
            if (bean.getTrendValue(KParamType.URINERT_GLU) == GlobalConstant.INVALID_DATA) {
                uriMeasure = getString(R.string.no_check);
            } else {
                uriMeasure = getString(R.string.is_checked);
            }
            gvMeasureData.add(uriName + " " + colon + uriMeasure);
        }
        if ((paramValue & (0x01 << 4)) != 0
                || (paramValue & (0x01 << 5)) != 0) { //体温
            String tempValue = MeasureUtil.formatMeasureData(KParamType.IRTEMP_TREND,
                    bean.getTrendValue(KParamType.IRTEMP_TREND));
            gvMeasureData.add(tempValue);
        }
        String heightValue = MeasureUtil.formatMeasureData(KParamType.HEIGHT,
                bean.getTrendValue(KParamType.HEIGHT));
        String weightValue = MeasureUtil.formatMeasureData(KParamType.WEIGHT,
                bean.getTrendValue(KParamType.WEIGHT));
        String bmiValue = MeasureUtil.formatMeasureData(KParamType.BMI,
                bean.getTrendValue(KParamType.BMI));
        if (measureConfig == 3) { //身高+体重
            gvMeasureData.add(heightValue);
            gvMeasureData.add(weightValue);
            gvMeasureData.add(bmiValue);
        } else if (measureConfig == 1) { //身高
            gvMeasureData.add(heightValue);
        } else if (measureConfig == 2) { //体重
            gvMeasureData.add(weightValue);
        }
        gvMeasureAdapter.notifyDataSetChanged();
    }

    private BroadcastReceiver usbStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //usb连接
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                //初始化一体机读卡器
                initReadCardDevice();
            } else if (BroadcastUtils.ADD_PATIENT.equals(action)) { //新增居民 刷新界面
                isAddNewUser = true;
                tempContent = "";
                tempIsQuery = true;
                tempSex = 0;
                tempUploadState = 0;
                tempStart = null;
                tempStop = null;
                refreshPatient(presenter.getAllPatientBean(0, 10));
            } else if (BroadcastUtils.REPLACE_PATIENT.equals(action)) {
                initMeasureData();
            } else if (BroadcastUtils.HEALRH_MEASURE_CARD_READER.equals(action)) {
                String idcard = intent.getStringExtra(IDCARD);
                String name = intent.getStringExtra(GlobalConstant.NAME);
                String address = intent.getStringExtra(GlobalConstant.ADDRESS);
                byte[] picByte = intent.getByteArrayExtra(GlobalConstant.PICTURE);
                getInfoFromCard(name, idcard, 0, 0, address, picByte);
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { //usb断开连接
                stopReadCard();
            } else if (BroadcastUtils.SHOW_ADDPATIENT.equals(action)) {
                isShowHealthFile = true;
                isShowAddPatient = true;
                BroadcastUtils.sendOnStartForHealthMeasure();
            } else if (BroadcastUtils.DISMISS_ADDPATIENT.equals(action)) {
                isShowHealthFile = false;
                isShowAddPatient = false;
                BroadcastUtils.sendOnStopForHealthMeasure();
            } else if (BroadcastUtils.HEALTH_FILE_UPLOAD_DB.equals(action)) {
                showLoadingDialog(getString(R.string.uploading_db));
            } else if (BroadcastUtils.HEALTH_FILE_UPLOAD_DB_SUCCESS.equals(action)) {
                dismissLoadingDialog();
                ToastUtils.showShortToast(R.string.update_completed);
            } else if (BroadcastUtils.REFRSH_PATIENT.equals(action)) {
                //重新刷新病人状态
                refreshPatient();
            } else if (BroadcastUtils.SET_CURRENT_PATIENT.equals(action)) {
                //下载完成后返回该页面若当前用户为空则默认为列表的第一个用户为当前用户
                if (currentPatient == null) {
                    if (patientBeen != null && patientBeen.size() > 0) {
                        UiUtils.setCurrentPatient(patientBeen.get(0).getIdcard());
                    }
                }
            } else if (BroadcastUtils.REFRESH_NEW_DATA.equals(action)) {
                //体检报告列表删除测量记录后刷新数据
                initMeasureData();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_close:
                final List<String> deletePatient = patientAdapter.getDeletePatient();
                if (deletePatient != null && deletePatient.size() > 0) {
                    popupDialog = new PopupDialog(this,
                            UiUtils.getString(R.string.delete_patient),
                            new PopupDialog.UpdateButtonState() {

                                @Override
                                public void getButton(Boolean pressed) {

                                    popupDialog.dismiss();
                                    if (pressed) {
                                        showLoadingDialog(UiUtils.getString(R.string.deleting));
                                        presenter.deletePatient(deletePatient, isAllSelected,
                                                tempContent, tempStart, tempStop, tempSex
                                                , tempUploadState, tempIsQuery, loadingDialog);
                                    }
                                }

                                @Override
                                public void close() {
                                    popupDialog.dismiss();
                                }
                            });
                    popupDialog.show();
                    popupDialog.setContent(UiUtils.getString(R.string.delete_patient_msg));
                } else {
                    ToastUtils.showShortToast(R.string.please_select_patient);
                }
                break;
            case R.id.et_query_condition:
                etQueryCondition.setCursorVisible(true);
                break;
            case R.id.iv_clear:
                etQueryCondition.setText("");
                etQueryCondition.setCursorVisible(false);
                break;
            case R.id.tv_start_time:
                datePickerDialog.show();
                break;
            case R.id.tv_stop_time:
                datePickerDialog.show();
                break;
            case R.id.iv_query: //根据身份证查询按钮
                QueryItem queryItem = new QueryItem();
                queryItem.setName(etQueryCondition.getText().toString());
                queryItem.setQuery(true);
                List<PatientBean> patientBeen = queryPatient(queryItem);
                resolveData(patientBeen, true);
                break;
            case R.id.btn_select:
                //筛选按钮
                //点击筛选后的弹窗
                selectDialog = new SelectDialog(this
                        , new SelectDialog.OnQueryListener() {
                                @Override
                                public void onQuery(QueryItem item) {
                                    //筛选条件
                                    List<PatientBean> patientBeanList = queryPatient(item);
                                    resolveData(patientBeanList, false);
                                    if (selectDialog.isShowing()) {
                                        selectDialog.dismiss();
                                    }
                                }

                                @Override
                                public void clearSelection() {
                                    //清空筛选条件后数据还原
                                    isReset = true;
                                    QueryItem queryItem = new QueryItem();
                                    queryItem.setName(etQueryCondition.getText().toString());
                                    queryItem.setQuery(true);
                                    List<PatientBean> patientBeen = queryPatient(queryItem);
                                    resolveData(patientBeen, true);
                                }
                        });
                selectDialog.show();
                break;
            case R.id.btn_download:
                //下载按钮
                CheckData checkData = ProviderReader.getCheckData(this);
                if (checkData == null) {
                    ToastUtils.showShortToast(R.string.default_user_no_download);
                    return;
                }
                Intent intent = new Intent(this, PatientDownloadActivity.class);
                startActivity(intent);
                //注销广播避免该页面接收到刷身份证信息在下载页面刷身份证的时候
                unregisterReceiver(usbStateReceiver);
                break;
            case R.id.iv_modify:
                if (currentPatient == null) {
                    ToastUtils.showShortToast(R.string.please_set_current_patient);
                } else {
                    Intent alterIntent = new Intent(this, AlterPatientActivity.class);
                    startActivity(alterIntent);
                }
                break;
            case R.id.iv_report:
                //子线程执行数据查询判断是否有测量数据
                presenter.initReportData();
                break;
            default:
                break;
        }
    }

    /**
     * 查询完后的数据处理
     * @param list 查询的数据
     * @param isQueryFlag 区分查询和筛选标识
     */
    private void resolveData(List<PatientBean> list, boolean isQueryFlag) {
        if (list == null) {
            ToastUtils.showShortToast(R.string.measure_time_error);
            return;
        }
        this.patientBeen.clear();
        this.patientBeen.addAll(list);
        if (this.patientBeen == null || this.patientBeen.size() == 0) {
            ToastUtils.showShortToast(R.string.select_empty);
        } else {
            if (isReset) {
                isReset = false;
                ToastUtils.showShortToast(R.string.reset_success);
            } else {
                ToastUtils.showShortToast(R.string.select_success);
            }
        }
        if (isQueryFlag) {
            tvTotalPatient.setText(presenter.getPatientSize(tempContent
                    , tempStart, tempStop));
        } else {
            tvTotalPatient.setText(presenter.getPatientSizeInSelect(tempSex, tempUploadState
                    , tempStart, tempStop));
        }
        Log.e("xsc_tvtotal_3", "" + tvTotalPatient.getText().toString());
        patientAdapter.setAllSize(allSize);
        patientAdapter.notifyDataSetChanged();
        UiUtils.hideKeyboard(etQueryCondition);
    }

    @Override
    public void showReport(HealthReportActivity.ReportState state, List<MeasureDataBean> data) {
        dismissLoadingDialog();
        switch (state) {
            case SHOW_DATA:
                UiUtils.setMeasureDataBeen(data);
                Intent intent = new Intent(this, ReportListActivity.class);
                startActivity(intent);
                isShowHealthFile = false;
                break;
            case EMPTY_MEASURE:
                ToastUtils.showShortToast(R.string.empty_measure_data);
                break;
            case EMPTY_PATIENT:
                ToastUtils.showShortToast(R.string.current_patient_empty);
                break;
            default:
                break;
        }
    }

    /**
     * 根据组合筛选获取居民列表
     * @param queryItem 查询条件
     * @return 居民列表
     */
    public List<PatientBean> queryPatient(QueryItem queryItem) {
        //开始时间
        String starTime = queryItem.getMeasureStart();
        //结束时间
        String stopTime = queryItem.getMeasureEnd();
        //姓名或身份证
        String condition = queryItem.getName();
        int uploadState = queryItem.getUpload();
        int sex = queryItem.getSex();
        Date startDate;
        Date stopDate;
        try {
            if (TextUtils.isEmpty(starTime)
                    || starTime.contains(UiUtils.getString(R.string.measure_time))
                    || starTime.contains(UiUtils.getString(R.string.measure_start_time))) {
                startDate = null;
            } else {
                startDate = sdf.parse(starTime);
            }
            if (TextUtils.isEmpty(stopTime)
                    || stopTime.contains(UiUtils.getString(R.string.measure_time))
                    || stopTime.contains(UiUtils.getString(R.string.measure_end_time))) {
                stopDate = null;
            } else {
                stopDate = sdf.parse(stopTime);
            }
            if (startDate != null && stopDate != null) {
                if (startDate.compareTo(stopDate) > 0) {
                    return null;
                }
            }
            cbxAllSelect.setChecked(false);
            patientAdapter.setAllDeleteState(false);
            tempStart = startDate;
            tempStop = stopDate;
            tempContent = condition;
            tempUploadState = uploadState;
            tempSex = sex;
            tempIsQuery = queryItem.isQuery();
            return presenter.getPatientBean(condition, startDate, stopDate, uploadState, sex
                    , 0, 10, tempIsQuery);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }


    @Override
    public void addPatient(List<PatientBean> list) {
        patientBeen.addAll(list);
        patientAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshPatient(List<PatientBean> list) {
        patientBeen.clear();
        patientBeen.addAll(list);
        cbxAllSelect.setChecked(false);
        isAllSelected = false;
        patientAdapter.setAllDeleteState(false);
        patientAdapter.notifyDataSetChanged();

        if (tempIsQuery) {
            tvTotalPatient.setText(presenter.getPatientSize(tempContent
                    , tempStart, tempStop));
        } else {
            tvTotalPatient.setText(presenter.getPatientSizeInSelect(tempSex, tempUploadState
                    , tempStart, tempStop));
        }
        allSize = presenter.getAllPatientSize();
//        tvTotalPatient.setText(allSize + "");
        Log.e("xsc_tvtotal_4", "" + tvTotalPatient.getText().toString());
        patientAdapter.setAllSize(allSize);
        dismissLoadingDialog();
    }

    @Override
    public void deletePatient(List<String> list) {
        List<PatientBean> delete = new ArrayList<>();
        for (PatientBean bean : patientBeen) {
            if (list.contains(bean.getIdcard())) {
                delete.add(bean);
            }
        }
        patientBeen.removeAll(delete);
        cbxAllSelect.setChecked(false);
        isAllSelected = false;
        patientAdapter.setAllDeleteState(false);
        patientAdapter.notifyDataSetChanged();

        if (tempIsQuery) {
            tvTotalPatient.setText(presenter.getPatientSize(tempContent
                    , tempStart, tempStop));
        } else {
            tvTotalPatient.setText(presenter.getPatientSizeInSelect(tempSex, tempUploadState
                    , tempStart, tempStop));
        }

        allSize = presenter.getAllPatientSize();
        patientAdapter.setAllSize(allSize);
//        tvTotalPatient.setText(allSize + "");
        Log.e("xsc_tvtotal_5", "" + tvTotalPatient.getText().toString());
        dismissLoadingDialog();
    }

    @Override
    public List<PatientBean> notDeletePatient() {
        //点击全选后，又对某些居民进行取消删除状态。获取该操作下的居民
        return patientAdapter.getNotDeletePatient();
    }

    /**
     * 刷卡子线程
     */
    public class BrushCardThread extends Thread {
        @Override
        public void run() {
            while (runThread) {
                if (!isUsbConnectedDevice || !isShowHealthFile) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                //获取卡信息
                brushIdCard();
                brushHealthCard();
                mtIdCard();
                mtHealthCard();
                dkReadHealthCard();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 明泰身份证读取
     */
    public void mtIdCard() {
        //为空或者usb没有连接上时，不进行读取。
        if (mtReader == null || !mtReader.getMtDeviceConnect()) {
            return;
        }
        if (!mtReader.getMtPortState() && mtReader.getMtDeviceConnect()) {
            mtReader.reGetMTPermission();
            mtReader.openDevice();
        }
        int st = 0;
        int[] nRecLen = new int[8];
        final byte[] szName = new byte[128];
        byte[] szSex = new byte[128];
        byte[] szNation = new byte[128];
        byte[] szBirth = new byte[128];
        byte[] szAddress = new byte[128];
        byte[] szIDNo = new byte[36];
        byte[] szDepartment = new byte[128];
        byte[] szDateStart = new byte[128];
        byte[] szDateEnd = new byte[128];
        final byte[] szdata = new byte[3072];
        st = mtReader.mt8IDCardRead(
                szName,
                szSex,
                szNation,
                szBirth,
                szAddress,
                szIDNo,
                szDepartment,
                szDateStart,
                szDateEnd,
                nRecLen,
                szdata);
        if (st != 0) {
            //读取身份证信息失败
        } else {
            try {
                final int type = 0;
                final String name = new String(szName, "UTF-16LE").trim();
                final String idCard = new String(szIDNo, "UTF-16LE");
                char s = idCard.charAt(16);
                final int sex = Integer.valueOf(s);
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        getInfoFromCard(name, idCard, sex, type, "", null);
                    }
                });
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 明泰健康卡
     */
    public void mtHealthCard() {
        if (mtReader == null || !mtReader.getMtDeviceConnect()) {
            return;
        }
        if (!mtReader.getMtPortState() && mtReader.getMtDeviceConnect()) {
            mtReader.reGetMTPermission();
            mtReader.openDevice();
        }
        byte[] name = new byte[40];
        byte[] sex = new byte[5];
        byte[] nation = new byte[5];
        byte[] idcardno = new byte[20];
        byte[] birth = new byte[10];
        byte[] departName = new byte[40];
        byte[] departTime = new byte[10];
        byte[] validTime = new byte[10];
        byte[] photo = new byte[3080];
        byte[] photoAsc = new byte[3080 * 2];
        byte[] addr1 = new byte[110];
        byte[] addr2 = new byte[110];
        byte[] lpErrMsg = new byte[512];
        int st = mtReader.ReadHealthCard(name, sex, nation, idcardno, birth, departName,
                departTime, validTime, photo, addr1, addr2, lpErrMsg);
        if (st == 0) {
            try {
                final int type = 0;
                final String nameStr = new String(name, "gb2312").trim();
                final String idCard = new String(idcardno, "gb2312").trim();
                char s = idCard.charAt(16);
                final int sexInt = Integer.valueOf(s);
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        getInfoFromCard(nameStr, idCard, sexInt, type, "", null);
                    }
                });
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过华大一体机刷身份证获取基本信息
     */
    public void brushIdCard() {
        if (huaDaDeviceLib == null) {
            return;
        }
        int re = 0;
        // For IDcard
        byte[] name = new byte[32];
        byte[] sex = new byte[6];
        byte[] birth = new byte[18];
        byte[] nation = new byte[12];
        byte[] address = new byte[72];
        byte[] department = new byte[32];
        byte[] idno = new byte[38];
        byte[] effectDate = new byte[18];
        byte[] expireDate = new byte[18];
        byte[] errMsg = new byte[20];
        byte[] bmpFile = new byte[38556];

        final int pSex = 1;
        final int type = 0;
        String pkName = "aaaa";
        try {
            if (!huaDaDeviceLib.isOpen()) {
                return;
            }
            re = huaDaDeviceLib.PICC_Reader_ReadIDMsg(bmpFile, name,
                    sex, nation, birth, address, idno, department,
                    effectDate, expireDate, errMsg, pkName);
            if (re < 0) {
                return;
            } else {
                final String pName = (new String(name, "Unicode")).replace(" ", "");
                final String idcard = new String(idno, "Unicode");
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        getInfoFromCard(pName, idcard, pSex, type, "", null);
                    }
                });
            }
        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (Exception eint) {

            eint.printStackTrace();
        }
    }

    /**
     * 通过华大一体机刷健康卡获取信息
     */
    public void brushHealthCard() {
        if (huaDaDeviceLib == null) {
            return;
        }
        if (!huaDaDeviceLib.isOpen()) {
            return;
        }
        try {
            //PSAM上电成功标识
            int flag1 = huaDaDeviceLib.powernOnPSAM();
            String password = "123456";
            //PSAM校验标识
            int flag2 = huaDaDeviceLib.verificationPSAM(password);
            //健康卡上电标识
            int flag3 = huaDaDeviceLib.powernOnHealthCard();
            byte[] klb = new byte[4];    //卡的类别
            byte[] gfbb = new byte[16];   //规范版本
            byte[] fkjgdm = new byte[64]; //初始化机构编号
            byte[] fkjgzs = new byte[360]; //发卡机构证书
            byte[] fkjgmc = new byte[64]; //初始化机构编号
            byte[] fkrq = new byte[8];   //发卡日期
            byte[] kyxq = new byte[8];    //卡有效期
            byte[] kh = new byte[18];      //卡号
            byte[] aqm = new byte[3];      //安全码
            byte[] xpxlh = new byte[10];      //芯片序列号
            byte[] yycsdm = new byte[8];      //应用城市代码
            byte[] err = new byte[64];       //错误信息
            int flag4 = 0;
            //获取健康卡发卡机构信息是否成功标识
            flag4 = huaDaDeviceLib.readIssuerAgency(klb, gfbb, fkjgdm, fkjgzs,
                    fkjgmc, fkrq, kh, aqm, xpxlh, yycsdm, err);

            if (flag1 > 0 && flag2 == 1 && flag3 > 0 && flag4 >= 0) {
                int nRet = 0;
                byte[] chsXM = new byte[30];            //姓名
                byte[] chsXB = new byte[2 + 1];         //性别代码
                byte[] chsMZ = new byte[2 + 1];         //民族代码
                byte[] chsCSRQ = new byte[8 + 1];       //出生日期，YYYYMMDD格式
                byte[] chsSFZH = new byte[18];          //居民身份证号

                final int pSex = 0;
                final int type = 0;

                nRet = huaDaDeviceLib.readPersonalInformation(chsXM, chsXB,
                        chsMZ, chsCSRQ, chsSFZH);
                if (nRet < 0) {
                    return;
                } else {
                    final String pName = new String(chsXM, "GBK");
                    final String idcard = new String(chsSFZH);
                    UiUtils.post(new Runnable() {
                        @Override
                        public void run() {
                            getInfoFromCard(pName, idcard, pSex, type, "", null);
                        }
                    });
                }
            } else {
                return;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception eint) {
            eint.printStackTrace();
        }
    }

    /**
     * 德卡刷健康卡
     */
    private void dkReadHealthCard() {
        if (dkRead == null) {
            return;
        }
        final int portState = dkRead.portOpen("USB", 0); //打开usb权限

        if (portState == 0) { //打开端口成功
            try {
                String data = dkRead.readHealthCard(); //读取健康卡
                String[] datas = data.split("\\|");
                String id = datas[0]; //卡号
                final String idCard = datas[1]; //身份证号；
                final String name = new String(DigitalTrans
                        .hexStringToByteReal(datas[2]), "GBK"); //姓名
                final int pSex = 1;
                final int type = 0;
                String nation = datas[4]; //名族
                String birthday = datas[5]; //生日
                UiUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        getInfoFromCard(name, idCard, pSex, type, "", null);
                    }
                });
            } catch (Exception e) {
            }
        } else { //打开端口失败

        }
    }

    /**
     * 获取信息更新view
     * @param name 姓名
     * @param idcard 身份证
     * @param sex 性别
     * @param type 类型
     * @param address 地址
     * @param headPic 头像字节数组
     */
    public synchronized void getInfoFromCard(String name, String idcard, int
            sex, int type, String address, byte[] headPic) {
        if (!isShowHealthFile && !isShowAddPatient) {
            return;
        }
        if (!UiUtils.isMemoryEnough(GlobalConstant.MIN_SPACE_FOR_APP)) {
            ToastUtils.showShortToast(R.string.space_low);
        }
        if (idcard != null && idcard.length() == 18) {
            if (!UiUtils.isNumber(idcard.substring(0, 17))) {
                return;
            }
        }

        String currentIdCard = SpUtils.getSp(this, GlobalConstant.APP_CONFIG, GlobalConstant
                .CURRENT_PATIENT, "");
        //存在,不需要切换居民
        if (currentIdCard.equals(idcard) && !isShowAddPatient) {
            return;
        }
        //规避姓名特殊字符和空格
        name = name.replaceAll(" ", "");
        name = name.replaceAll("\\u0000", "");
        if (TextUtils.isEmpty(address)) {
            address = "";
        }
        address = address.replaceAll("\\u0000", "");
        //查询数据库是否存在该身份证
        List<PatientBean> list = DBUtitl.queryIdCard(this, idcard);
        if (list.size() > 0 && !isShowAddPatient) {  //存在,需要切换居民
            UiUtils.setCurrentPatient(idcard);
        } else {
            Intent intent = new Intent(this, AddPatientActivity.class);
            intent.putExtra(IDCARD, idcard);
            intent.putExtra(GlobalConstant.NAME, name);
            intent.putExtra(GlobalConstant.ADDRESS, address);
            intent.putExtra(GlobalConstant.PICTURE, headPic);
            startActivity(intent);
            BroadcastUtils.sendReadCardForAdd(idcard, name, address, headPic);
        }
        if (huaDaDeviceLib != null) {
            huaDaDeviceLib.demoBeepOn();
        }
    }

    /**
     * 设置全选状态
     * 先取消监听事件，再绑定
     * @param isAllCheck 全选状态
     */
    public void setAllSelect(boolean isAllCheck) {
        cbxAllSelect.setOnCheckedChangeListener(null);
        cbxAllSelect.setChecked(isAllCheck);
        cbxAllSelect.setOnCheckedChangeListener(listener);
    }

    @Override
    public HealthFilePresenterImpl initPresenter() {
        return new HealthFilePresenterImpl();
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        calendar.set(year, monthOfYear, dayOfMonth);
        tvCurrentTime.setText(this.sdf.format(calendar.getTime()));
        tvCurrentTime.setTextColor(UiUtils.getColor(R.color.title_color));
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {

    }

    /**
     * 显示进度条
     * @param content 进度条内容
     */
    private void showLoadingDialog(String content) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this, "");
            loadingDialog.setOnKeyListener(keyListener);
        }
        loadingDialog.show();
        loadingDialog.setContent(content);
    }

    /**
     * 关闭进度条
     */
    private void dismissLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4) { //F1
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isShowHealthFile = false;
        BroadcastUtils.sendHideForStartManage();
        stopReadCard();
    }

    /**
     * 停止刷卡
     */
    private void stopReadCard() {
        //该广播通知健康测量软件，停止内置刷卡服务
        if (mtReader != null) {
            mtReader.setMtPortOpen(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (usbStateReceiver != null) {
            unregisterReceiver(usbStateReceiver);
        }
        if (brushCardThread != null) {
            brushCardThread.interrupt();
        }
        huaDaDeviceLib = null;
        dkRead = null;
        mtReader = null;
        runThread = false;
        isUsbConnectedDevice = false;
    }
}
